﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

namespace Just4Devs.Vsirc.Addin.UI
{
    public partial class VsircChatScreen : UserControl
    {
        private Font _defaultFont;
        private Color _defaultColor;

        public VsircChatScreen()
        {
            InitializeComponent();

            _defaultColor = Color.Black;
            _defaultFont = chatRichTextBox.Font;
        }

        private void AppendTextToOutput(string text, Color color, Font font)
        {
            try
            {
                this.UIThreadInvoke(() => chatRichTextBox.AppendText(text));
                this.UIThreadInvoke(() => chatRichTextBox.ScrollToCaret());

                if (!string.IsNullOrEmpty(text))
                {
                    this.UIThreadInvoke(() =>
                    {
                        chatRichTextBox.SelectionStart = chatRichTextBox.TextLength - text.Length;
                        chatRichTextBox.SelectionLength = text.Length;
                        chatRichTextBox.SelectionColor = color;
                        chatRichTextBox.SelectionFont = font;
                        chatRichTextBox.SelectionStart = chatRichTextBox.TextLength;
                        chatRichTextBox.SelectionLength = 0;
                        chatRichTextBox.SelectionColor = Color.Black;
                    });
                }

                Application.DoEvents();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message);
            }
        }

        private void AppendTextToOutput(string text)
        {
            AppendTextToOutput(text, _defaultColor, _defaultFont);
        }

        public void HandleMessage(ScreenMessage message)
        {
            foreach (var messagePart in message.Parts)
            {
                if (!string.IsNullOrEmpty(messagePart.Text))
                {
                    AppendTextToOutput(messagePart.Text + ScreenMessage.Whitespace, messagePart.TextColor, _defaultFont);
                }
            }

            AppendTextToOutput(Environment.NewLine);
        }
    }
}
